#include <stdio.h>
#include <string.h>
#include "QHDX_main.h"

void UserLoginFun(int ID)
{
	UserLogin LoginInfo, CheckInfo, UpInfo;
	struct StudentInfo Student;
	int number, flag = 0;
	printf("\n请先登录！\n");
	
	while(1)
	{
		printf("\n请输入用户名:>");
		scanf("%s", &LoginInfo.User_Name);
	
		//回显
		strcpy(&LoginInfo.User_Pass, getpass("\n请输入密码:>"));
		number = atoi(LoginInfo.User_Name);
		//是否第一次登录	
		if(Is_FirstLogin() == 1)
		{
			if (ID == 1 || ID == 3)
			{	
				if(1 != Is_Student_Exist(number) || (strcmp(&LoginInfo.User_Pass, "123456") != 0))
				{
					printf("\n用户名或密码有误，请重新登录！\n");
					while(getchar() != '\n');
				}
				else
				{
					flag = 1;
					break;
				}
			}
			if (ID == 2)
			{	
				if(strcmp("admin", &LoginInfo.User_Name) != 0 || strcmp("123456", &LoginInfo.User_Pass) != 0)
				{
					printf("\n用户名或密码有误，请重新登录！\n");
					while(getchar() != '\n');
				}
				else
				{ 
					flag = 1;
					break;
				}		
			}
		}
		else
		{	
			char EncodePass[31];
			FILE* fp = fopen("LoginData", "rb");
			fread(&CheckInfo, sizeof(CheckInfo), 1, fp);
			md5_encode(&LoginInfo.User_Pass, strlen(LoginInfo.User_Pass), EncodePass);
			if(strcmp(&LoginInfo.User_Pass, EncodePass) != 0 ||strcmp(&LoginInfo.User_Name, &CheckInfo.User_Name) != 0)
			{
				printf("\n用户名或密码有误！请重新登录！\n");
				while(getchar() != '\n');
			}
			else break;
		}
	}
	
	if(flag == 1)
	{	
		char CheckPass[31], UserPass[31];
		//首次登录修改密码
		printf("\n为了系统安全，请重新重新设置用户名和密码\n");
		printf("用户名:>");
		scanf("%s", LoginInfo.User_Name);
		while(1)
		{
			strcpy(UserPass, getpass("用户密码:>"));
			strcpy(CheckPass, getpass("再次输入密码:>"));
			if(strcmp(UserPass, CheckPass) != 0)
			{
				printf("\n两次输入密码不一样，请重新输入!\n");
			}
			else break;
		}
		printf("1111111111111111111111111111");
		//md5_encode(UserPass, strlen(UserPass), LoginInfo.User_Pass);
		FILE* fp = fopen("LoginData", "wb");
		fwrite(&LoginInfo, sizeof(LoginInfo), 1, fp);
		fclose(fp);
		printf("\n成功修改用户和密码，请牢记！\n");
	}
	
	printf("\n恭喜您！登录成功!\n");
	
}

int Is_FirstLogin(void)
{
	FILE *fp = fopen("UserLoginData", "rb");
	if(fp == NULL) return 1;
	fclose(fp);
	return 0;
}
